package esiag.pds.InformationManager;

import pds.esiag.cache.beans.HeartBeat;
import esiag.interfaces.IObserver;
import esiag.pds.beans.Information;
import esiag.pds.jms.Sender;
import esiag.psd.cacheManager.CacheManager;

public class NEWInformationManager extends Thread implements IObserver {

	private HeartBeat heartBeat;
	private Sender sender;
	static int cp=1;
	//private MessageInOut m;
	private CacheManager cm;
	private InformationProvider informationProvider;
	private boolean currentstate=true;
	private static boolean isreachable=true;
	
	public NEWInformationManager(HeartBeat hb,CacheManager cm,String queue,String url)  {
		// TODO Auto-generated constructor stub
		informationProvider=new InformationProvider();
		this.cm=cm;
		sender=new Sender(cm,queue,url);
		heartBeat=hb;
	}
	public void update(boolean reachable) {
		// TODO Auto-generated method stub
		isreachable=reachable;
	}
	
	public void run(){
		while(true){
			isreachable=heartBeat.getServerState();
			if(!isreachable){
				System.out.println("\n $$$$$ Information put in cahe $$$$$");
				addToCache(informationProvider.getInformation());
				if(isreachable!=currentstate)
				{
					System.out.println("\n\t\t\t\t====> Control center is Unreachable .. <====\n");
					currentstate=isreachable;
					cm.ManagingCache();	
				}
			}
			else{
					if(isreachable!=currentstate)
					{
						System.out.println("\n\t\t\t\t====> Control center is Reachable .. <====\n");
						currentstate=isreachable;
					}
					if(cm.getCache().getSize()>0){
						addToCache(informationProvider.getInformation());
						sender.send();
					}
					else
						sender.send(informationProvider.getInformation()); 
				}
			try {
				Thread.sleep(2000);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	
	void addToCache(Information inf ){
		cm.getCache().add(inf);
		for (int i = 0; i < cp ; i++) {
			cm.getCache().add(inf);
		}
		cp++;
	}

}
